<template>
  <div class="comdiv">

    <div class="con" ref="bgImage">
      <!-- search1 -->
      <search-temp
        :listQuery="listQuery.searchText"
        @doSearch="handleFilter"
        @handleCreate="handleCreate"
        :placeholder="placeholder"
      ></search-temp>

      <el-table :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
        <el-table-column align="center" label="序号">
          <template slot-scope="scope"><span>{{scope.row.px}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="角色">
          <template slot-scope="scope"><span>{{scope.row.roleName}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="标记名">
          <template slot-scope="scope"><span>{{scope.row.roleCode}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="warning" plain @click="handleResource(scope.row)" size="small">
              权限
            </el-button>
            <el-button type="primary" plain @click="handleUpdate(scope.row)" size="small">
              修改
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :title="dialogStatus=='create'?'添加角色':'修改角色'" :visible.sync="dialogFormVisible">
        <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px"
                 style='width: 450px; margin-left:50px;'>
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="temp.roleName"></el-input>
          </el-form-item>
          <el-form-item label="标记名" prop="roleCode">
            <el-input v-model="temp.roleCode"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData" id="cfmbtm1">确定</el-button>
          <el-button v-else type="primary" @click="updateData" id="cfmbtm2">确定</el-button>
        </div>
      </el-dialog>

      <!--权限展示-->
      <el-dialog :title="roleRow.roleName+' 权限配置'" :visible.sync="dialogResourceShow">
        <div v-show="myLoading" class="el-loading-spinner"><i class="el-icon-loading"></i>
          <p class="el-loading-text">拼命加载中</p></div>
        <el-tabs v-model="activeTab" @tab-click="getGroupResources" tab-position="left" type="border-card">
          <el-tab-pane
            style="min-height:10vh;"
            :key="item._id"
            v-for="(item, index) in tabItems"
            :label="item.groupName"
            :name="item._id+''"
          >
            <div v-show="tabsMyLoading" class="el-loading-spinner"><i class="el-icon-loading"></i>
              <p class="el-loading-text">权限加载中...</p></div>
            <el-checkbox-group v-model="roleChoseGR" @change="changeSelect" size="small" >
              <el-checkbox v-for="it in groupResources" :key="it._id" :name="it.resourceName" :label="it._id" border>{{it.resourceName}}</el-checkbox>
            </el-checkbox-group>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
  </div>
</template>

<script>

  import {fetchGet, createOne, deleteOnePut, updateOneNoId} from '@/api/common'
  import {disableBtn, df, $err, $suc, ERRS, SUCS} from '@/utils'
  import searchTemp from '@/components/viewComponents/search'

  export default {
    name: 'roleList',
    // search2 引入 and search3 声明
    components: {searchTemp},

    data() {
      return {
        url: 'auth/roles',
        list: null,
        total: 0,
        px: null, //最大序号
        listLoading: true,
        myLoading: true,
        tabsMyLoading: true,
        placeholder: '角色', //search4
        listQuery: {
          page: 1,
          size: 10, //每页几条
          number: 0, //当前页为第1页,从0计算
          searchText: undefined,
          sort: 'id'
        },
        //弹出层
        dialogFormVisible: false,
        //权限弹出层
        dialogResourceShow: false,
        roleRow:{},
        activeTab: '',
        tabItems:[],  //权限组
        groupResources:[],  //组中所有权限
        roleChoseGR:[], //角色选中的
        roleChoseOld:[], //角色选中的
        apiCnt:0, //接口调用关闭loading判断
        form: {
          type: [],
        },

        dialogStatus: '',
        temp: {},
        rules: {
          roleName: [
            {required: true, message: '请输入角色名', trigger: 'blur'}
          ],
          roleCode: [
            {required: true, message: '请输入标记名', trigger: 'change'},
          ]
        }
      }
    },
    mounted() {
      this.getList();
    },
    methods: {
      /* --- 权限分配 start  --- */
      changeSelect(aa){
        let bb=this.roleChoseOld
        let cc='';
        let checked=false
        if(aa.length>bb.length){  //add one aa比bb多一个元素
          [cc]= aa.filter(key => !bb.includes(key))
          checked=true
          console.log('++',cc)
        }else{  //reduce one
          [cc]= bb.filter(key => !aa.includes(key))
          console.log('--',cc)
        }
        if(!cc) return
        //取得选中的资源
        // let [res]=this.groupResources.filter(k=>k._id==cc)
        let param=
        {
          checked: checked,
          resId: cc,  //资源id
          roleId: this.roleRow._id  //角色id
        }
        updateOneNoId('auth/reses/checkedRes', param).then(res => {
          console.log(res.message)
          if (res.code === 0) {
            this.roleChoseOld=aa
            // console.log(res.message)
          } else {
            ERRS(res.message)
          }
        })

      },
      fetchTemp(url){
        //获取所有
        fetchGet(url).then(res => {
          console.log(res);
          if (res.code == 0) {
              let filt=res.data.map((v) => {
                if(v.checked) return v._id
              })
              this.roleChoseGR=filt.filter((s)=> s ? s:false) //已选中
              this.roleChoseOld=this.roleChoseGR //待比较
              this.groupResources=res.data  //全部数组
console.log(this.roleChoseGR,this.roleChoseOld)
            this.tabsMyLoading=false;
            //判断选项卡内容2重异步loading关闭
/*            this.apiCnt++ //v-if="apiCnt>1"
            if(this.apiCnt>1){
              this.tabsMyLoading=false;
            }
            return*/
          } else {
            ERRS(res.message)
          }
        })
      },
      //tabs切换
      getGroupResources(){
        this.tabsMyLoading=true
        let groupId=this.activeTab
        this.groupResources=[]
        console.log(999,this.roleRow)
        this.apiCnt=0;
        //所有的
        // this.fetchTemp(0,`auth/reses/group/${groupId}/all`);
        //角色所有 checked true选中的  false
        this.fetchTemp(`/auth/reses/role/${this.roleRow._id}/group/${groupId}`)
      },
      //分配权限
      handleResource(row) {
        this.roleRow=row
        this.dialogResourceShow = true;
        fetchGet('auth/resGroups/all').then(res => {
          console.log(res);
          if (res.code == 0) {
            this.tabItems = res.data
            this.activeTab = this.tabItems[0]._id+''
            console.log(this.activeTab,typeof this.activeTab)
            if(this.activeTab){
              this.getGroupResources()
            }
          } else {
            ERRS(res.message)
          }
          this.myLoading = false
        })


      },
      ////search5
      handleFilter(val) {
        this.listQuery.searchText = val;
        this.getList()
      },
      /* --- table start  --- */
      getList() {
        this.listLoading = true;
        fetchGet(this.url + '/all').then(res => {
          console.log(res);
          if (res.code == 0) {
            let dat = res.data
            // this.listQuery.size = dat.size ? dat.size : //每页几条
            // this.listQuery.page = dat.page ? dat.page : //当前页为第1页
            this.list = dat;
            let insIndex = this.listQuery.size * (this.listQuery.page - 1);
            this.list = this.list.map((v, index) => {
              this.$set(v, 'px', insIndex + index + 1);
              this.px = insIndex + index + 1; //最大序号
              return v
            });
            this.$nextTick()
          } else {
            ERRS(res.message)
          }
          this.listLoading = false
        })
      },

      /* -------         curd        ---------- */
      //添加
      handleCreate() {
        this.temp = {id: undefined, roleName: '', roleCode: ''},
          this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      //添加提交
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm1');
            createOne(this.url, this.temp).then(response => {
              this.getList();
              this.dialogFormVisible = false
              SUCS('创建成功')
            })
          }
        })
      },

      //详情修改
      handleUpdate(row) {
        this.temp = {id: row._id, roleName: row.roleName, roleCode: ''};
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      //修改提交
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm2');
            // delete tempData.createdTime;
            updateOneNoId(this.url + `/${this.temp.id}`, this.temp).then(res => {
              if (res.code === 0) {
                SUCS('修改成功!')
                this.getList();
              } else {
                ERRS(res.message)
              }
              this.dialogFormVisible = false
            })
          }
        })
      },
      //删除
      handleDelete(row) {
        console.log(row);
        this.$msgbox({
          // title: '删除',
          message: '确定要删除吗?',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          deleteOnePut(this.url + `/freeze`, row._id).then(res => {
            if (res.code === 0) {
              this.getList();
              SUCS('删除成功!')
            } else {
              ERRS(res.message)
            }
            this.dialogFormVisible = false
          })
        });
      },


    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  @import './comp/index.scss';
  .el-tabs--left, .el-tabs--right {
    height: 60vh;
  }

  .el-checkbox.is-bordered.el-checkbox--small {
    padding: 5px 10px 0px 10px;
    border-radius: 3px;
    height: 30px;
    margin-left: 10px;
    margin-bottom: 5px;
  }

</style>
